import os
from django.http.response import JsonResponse
# Create your views here.
from .models import FaceImage,Users,CatagoryAccess,CommunityInfo
from hashlib import md5
from django.db.models import F
from utils import regonize
# create

def createUser(req):
    try:
        img = req.FILES["faceImg"]
        imgth=FaceImage.objects.create(fileUrL=img)
        username=req.POST['username']
        password=req.POST['password']
        md=md5(password.encode())
        password=md.hexdigest()
        user1=Users.objects.create(name=username,password=password,avata_id=imgth.id)
        data={
            "username":user1.name,
            "imgurl":'/media/'+user1.avata.fileUrL.name,
            "access":user1.access
        }
        return JsonResponse({"code":200,
                             'msg': "success!!",
                             'data':data
                             })
    except Exception as e:
        return JsonResponse({"code": 400, "msg": e})


def loginUser(req):
    try:
        username = req.POST['username']
        user1=Users.objects.get(name=username)
        data={
            "username":user1.name,
            "imgurl":'/media/'+user1.avata.fileUrL.name,
            'access':user1.access
        }
        return JsonResponse({
            'code':200,
            'data':data
        })
    except Exception as e:
        print(e)
        return JsonResponse({
            'code':308,
            'msg':"user not exists or 没有使用post"
        })

def check_face(req,pi):
    try:
        buff=req.body
        path=os.path.join(os.path.dirname(__file__),'temp')+'/demo%d.jpg'%(pi,)
        with open(path,'wb') as f:
            f.write(buff)
        result,photoName=regonize(path)
        if photoName!='':
            p=FaceImage.objects.filter(fileUrL=photoName)[0]
            msg=p.users.name
        if result:
            # mqtt unlock
            CatagoryAccess.objects.filter(id=1).update(useFace=F('useFace')+1)
            return JsonResponse({"code": 200, "msg": msg})
        else:
            return JsonResponse({"code":203,'msg':"try again"})
    except Exception as e:
        print(e)
        return JsonResponse({"code":400,"msg":"error"})

from .pub_cmd import  publish
def open_way(req):
    username=req.POST["username"]
    try:
        Users.objects.get(name=username)
        CatagoryAccess.objects.filter(id=1).update(useApp=F('useApp') + 1)
        return JsonResponse(publish('access',username))
    except Exception as e:
        return JsonResponse({'code':404,'msg':"no access!"})

import traceback
def close_way(req):
    try:
        username=req.POST['username']
        if username=="root":
            return JsonResponse(publish('noneone', '100'))
        else:
            return JsonResponse({'code': 404, 'msg': "no access!"})
    except Exception as e:
        return JsonResponse({'code':400,'msg':"method error!!"})

def btn_access(req):
    CatagoryAccess.objects.filter(id=1).update(useBtn=F('useBtn') + 1)
    return JsonResponse(publish('access','someone!!'))


def get_comm_info(req):
    data=CommunityInfo.objects.all()
    li=[{"id":per.id,"data":per.content} for per in data]
    data2=CatagoryAccess.objects.get(id=1)
    l2={"usebtn":data2.useBtn,"useapp":data2.useApp,"useFace":data2.useFace}
    return JsonResponse({
        'code':200,
        'data':{
            'infos':li,
            'accessway':l2
        }
    })









